var config = require('../../../config.js')
var http = require('../../../utils/httpHelper.js')
Page({
  data: {
    userInfo:{},
    address:''
  },
  //事件处理函数
  onLoad: function (options) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    that.setData({userInfo:userInfo});
    //添加地址
    var id = options.id;
    if(id != ''){
      var data = {id:id};
      http.httpGet(config.clubApi.getAddrInfo,data,function(res){
        if(res.code == '200'){
          var address = res.data;
          that.setData({address:{id:id,name:address.name,address:address.address,tel:address.phone}})
        }
      });
    }
  },
  formSubmit: function (e){
    //提交表单
    var val = e.detail.value;
    if(this.data.address != ''){
      var data = {id:this.data.address.id,name:val.name,phone:val.tel,address:val.address}
      http.httpPut(config.clubApi.editAddress,data,function(res){
        if(res.code == '200') {
          wx.navigateBack();
          console.log("编辑地址成功");
        }else {
          //wx.navigateBack();
          console.log("编辑地址失败");
        }
      });
    }else {
      var data = {userId:this.data.userInfo.userId,name:val.name,phone:val.tel,address:val.address};
      http.httpPut(config.clubApi.addAddress,data,function(res){
        if (res.code == '200') {
          wx.navigateBack();
          console.log("添加地址成功");
        }else {
          //wx.navigateBack();
          console.log("添加地址失败");
        }
      });
    }
  },
  deleteAddress:function(){     
    if((this.data.address!='')&& (this.data.address.id!='')){
      var id = this.data.address.id;
      var data = {id:id};
      http.httpPut(config.clubApi.delAddress,data,function(res){
        if(res.code == '200'){
          wx.showToast({
            title: '删除地址成功！',
            icon: 'success',
            duration: 500
          })
          wx.navigateBack();
          console.log("删除地址成功");
        }else{
          //wx.navigateBack();
          console.log("删除地址失败");
        }
      });
    }else{
      console.log("删除地址失败");
    }
  }
})
